import React, { useMemo } from 'react';

import { Avatar as AntdAvatar, AvatarProps as AntdAvatarProps } from 'antd';
import cs from 'classnames';

import colors from '@/config/color';

export type AvatarProps = AntdAvatarProps & {};

const Avatar: React.FC<AvatarProps> = ({ className, children, ...rest }) => {
  const render = useMemo(() => {
    if (typeof children === 'string' && children.length) {
      const str = children.trim();

      if (str.length <= 2) {
        return str;
      }

      return str.slice(-2, str.length);
    }

    return children;
  }, [children]);

  const color = useMemo(() => {
    if (typeof children === 'string' && children.length) {
      const asciiCode = children.charCodeAt(children.length - 1);

      return colors[asciiCode % colors.length];
    }
  }, [children]);

  return (
    <AntdAvatar
      className={cs(className)}
      style={{ backgroundColor: color }}
      shape="square"
      {...rest}
    >
      {render}
    </AntdAvatar>
  );
};

export default Avatar;
